package org.sky.logger.clazz;

import java.util.ArrayList;
import java.util.List;

/**
 * 类加载实例化
 * 
 * @author gaofu
 *
 */
public abstract class Loader<T> {
	protected List<Clazz<T>> clazzList = new ArrayList<Clazz<T>>();

	/**
	 * 如果依赖类已加载, 则实例化对象
	 * 
	 * @param dependClassName 依赖类的类名
	 * @param objectClassName 对象类的类名
	 * @return
	 */
	public boolean addClazz(String dependClassName, String objectClassName) {
		Clazz<T> clazz = Clazz.newInstance(objectType(), dependClassName, objectClassName);
		return addClazz(clazz);
	}

	public boolean addClazz(T object) {
		try {
			Clazz<T> clazz = new Clazz<T>(object);
			return addClazz(clazz);
		} catch (Exception e) {
		}
		return false;
	}

	public boolean addClazz(Clazz<T> clazz) {
		if (clazz == null || clazz.getObject() == null || objectType() == null
				|| !objectType().isAssignableFrom(clazz.getObject().getClass())) {
			return false;
		}
		clazzList.add(clazz);
		return true;
	}

	public Clazz<T> getClazz() {
		return getClazz(0);
	}

	public Clazz<T> getClazz(int i) {
		Clazz<T> clazz = null;
		if (0 <= i && i <= clazzList.size() - 1) {
			clazz = clazzList.get(i);
		}
		return clazz;
	}

	/**
	 * 获取对象
	 * 
	 * @return
	 */
	public T getObject() {
		return getObject(0);
	}

	/**
	 * 获取对象
	 * 
	 * @param i
	 * @return
	 */
	public T getObject(int i) {
		T object = null;
		Clazz<T> clazz = getClazz(i);
		if (clazz != null) {
			object = clazz.getObject();
		}
		return object;
	}

	public boolean removeClazz(Clazz<T> clazz) {
		return clazzList.remove(clazz);
	}

	public List<Clazz<T>> getClazzList() {
		return clazzList;
	}

	public void setClazzList(List<Clazz<T>> clazzList) {
		this.clazzList = clazzList;
	}

	public int size() {
		return clazzList.size();
	}

	public abstract Class<T> objectType();

}
